package com.ljsw.fragment;

import java.net.SocketException;
import java.util.ArrayList;
import com.android.hdhe.uhf.main.SaomiaoUtil;
import com.android.hdhe.uhf.main.Util;
import com.android.hdhe.uhf.reader.UhfReader;
import com.ljsw.activity.R;
import com.ljsw.adapter.ZhouzxAdapter;
import com.ljsw.application.App;
import com.ljsw.dialog.DeleteDialog;
import com.ljsw.dialog.LoginDialog;
import com.ljsw.dialog.UserLoginDialog;
import com.ljsw.dialog.ZzxDialog;
import com.ljsw.entity.RenWuClass;
import com.ljsw.entity.User;
import com.ljsw.server.UpServer;
import com.ljsw.util.Constant;
import com.ljsw.util.DialogManager;
import com.ljsw.view.SaomiaoGridView;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 清分员指纹验证    页面进行指纹验证   目前是指纹完之后点击弹出提示框
 * 作者: 石锚
 * 版本: 1.0
 * 日期: 2015-10-21
 */
public class QingfyFragment extends BaseFragment implements OnClickListener{
	private View view;
	private ImageView leftImage,rightImage;//清分员指纹图片
	private FragmentManager fm;
	private DialogManager dialogManager;//弹出框管理类
	private ZzxDialog zzxDialog;//周转箱弹出框
	private DeleteDialog deleteDialog;//删除弹出框
	private LoginDialog loginDiolag;//登录弹出框
	private Bundle bundle;
	private Handler handler;//消息通知
	private String cid;//车牌号
	private String paigongdan="";//派工单
	private TextView qf_name1,qf_name2;//清分员名字1 清分员名字2
	private Button btn;
	ArrayList<RenWuClass> wancenglist;
	private LinearLayout zxlist_layout,//填充器（美化UI,周转箱）
	 					 zxlist_layout_view;//填充器（周转箱列表）
	private ZhouzxAdapter zhouzxAdapter;//我的任务适  开始扫描  适配器
	private SaomiaoGridView zzxgridView;//周转箱扫描
	
	private ArrayList<String> list = new ArrayList<String>();//要扫描的集合数据
	private ArrayList<String> boxlist = new ArrayList<String>();//传扫描的集合数据
	private ArrayList<String> copylist = new ArrayList<String>();//传扫描的集合数据
	
	private App app;//全局变量
	private UserLoginDialog useDialog;//登录弹出框
	private String userId;//用户登录的账号
	private String pwd;//用户登录的密码
	private User user;//登录用户
	private String qfId="";//清分员Id
	private TextView startsaomiao;//开始扫描
	private TextView zzxclear;//清空周转箱，重扫
	
	private String fristUserId=null;//用户登录的密码
	private boolean flag= true;//标识是否是第一次
	private boolean tflag = true;//控制扫描的标识
	private boolean sflag = false;//扫描控制器开关
	
	private UhfReader reader ; //超高频读写器 
	private SaomiaoUtil saomiao;
	
	@SuppressLint("HandlerLeak")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_qingfy, container, false);
		dialogManager = new DialogManager(getActivity());
		app = (App) getActivity().getApplication();//初始化全局变量
		//获取读写器实例，若返回Null,则串口初始化失败
		reader = UhfReader.getInstance();
		Util.initSoundPool(getActivity());// 初始化扫描的声音
		saomiao = new SaomiaoUtil(reader);// 创建扫描工具类
		deleteDialog = dialogManager.getDeleteDialog();
		useDialog = dialogManager.getUserLoginDialog();
		zzxDialog = dialogManager.getZzxDialog();
		loginDiolag = dialogManager.getLoginDialog();
		// 这里必须先获取当前的Activity 否则将不能找到 R.id.main_frame
		fm = getActivity().getSupportFragmentManager();
		zhouzxAdapter = new ZhouzxAdapter(getActivity());//周转箱显示适配器
		initView();
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				loginDiolag.dismiss();
				switch (msg.what) {
				case 0://提交成功	
					String zzxt =  (String) msg.obj;
					if(list.contains(zzxt)){
						
					}else{
						if (boxlist.contains(zzxt)) {
							Util.play(1, 0);
							list.add(zzxt);
							break;
						}
					}
					showView();
					break;
				case 1://提交失败
					reSubmit();
					zzxDialog.setTitle("超时链接");
					break;
				case 2:
					reSubmit();
					zzxDialog.setTitle("提交失败");
					break;
				case 3:
					FragmentTransaction ft = fm.beginTransaction();			
					RwwcFragment fragment = new RwwcFragment();
			        bundle.putString("cid", cid);
			        fragment.setArguments(bundle);
			        ft.addToBackStack(null);
			        ft.replace(R.id.main_frame, fragment).commit();
			        break;
				case 10://获取登录框回传的账号和密码
					Bundle bundle = msg.getData();
					userId = bundle.getString("name");
					pwd = bundle.getString("pwd");
					if(userId.equals(fristUserId)){//如果相同，则提示用户已经验证
						Toast.makeText(getActivity(), "请换其他用户验证", Toast.LENGTH_SHORT).show();
						useDialog.show();
					}else{
						yanzhengUser(userId, pwd);
					}
					break;
				case 11:
					//用户判断
					checkLogin();
					break;
				case 12:
					Toast.makeText(getActivity(), app.fanhuiMsg, Toast.LENGTH_SHORT).show();
					useDialog.show();
					break;
				case 13://登录失败 
					Toast.makeText(getActivity(), app.fanhuiMsg, Toast.LENGTH_SHORT).show();
					OnLoginClick();//重新登录
					break;
				}
			}
		};
		useDialog.setmHandler(handler);
		saomiao.setHandler(handler);
		return view;
	}
	/**
	 * 初始化控件
	 */
	public void initView(){
		zzxclear = (TextView) view.findViewById(R.id.zzx_clear_qf);
		zzxgridView = (SaomiaoGridView) view.findViewById(R.id.qflist);// 周转箱扫描
		zxlist_layout_view = (LinearLayout) view.findViewById(R.id.qflist_layout_view);
		zxlist_layout = (LinearLayout) view.findViewById(R.id.qflist_layout);// 填充器
		qf_name1 = (TextView) view.findViewById(R.id.qf_name1);//清分员1
		qf_name2 = (TextView) view.findViewById(R.id.qf_name2);//清分员2
		leftImage = (ImageView) view.findViewById(R.id.zhiwen1_qf);//清分员指纹图像
		rightImage = (ImageView) view.findViewById(R.id.zhiwen2_qf);//清分员指纹图像
		startsaomiao = (TextView) view.findViewById(R.id.startsaomiao_qf);// 开始扫描
		startsaomiao.setOnClickListener(this);
		zzxclear.setOnClickListener(this);
		btn = (Button) view.findViewById(R.id.but_qf);
		btn.setOnClickListener(this);
		bundle = getArguments();
		if (bundle != null) {	
			cid = bundle.getString("cid");//得到传过来的车牌号
			copylist = (ArrayList<String>) bundle.getSerializable("box");
			for (int i = 0; i < copylist.size(); i++) {
				boxlist.add(copylist.get(i));
			}
			for (int i = 0; i < boxlist.size(); i++) {
				System.out.println(boxlist.get(i));
			}
			wancenglist = (ArrayList<RenWuClass>) bundle.getSerializable("list");
			//得到父页面传过来的派工单
			for (int i = 0; i < wancenglist.size(); i++) {
				paigongdan+=wancenglist.get(i).getPaigongDan()+"_";
			}
		}
	}
	
	@Override
	public void onStart() {
		flag = true;//初始化第一个人登录的标识
		if(list.size()>0){//周转箱集合
			zxlist_layout_view.setVisibility(View.VISIBLE);
			zxlist_layout.setVisibility(View.GONE);//显示填充器
		}else{
			zxlist_layout_view.setVisibility(View.GONE);
			zxlist_layout.setVisibility(View.VISIBLE);//不显示填充器
		}
		super.onStart();
	}
	
	@Override
	public void onDestroy() {
		saomiao.close();
		if(reader!= null){//关闭扫描功能
			reader.close();
		}
		super.onDestroy();
	}
	
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.but_qf://确定点击
			String name2 = qf_name2.getText().toString();
			if(null != name2 && !"".equals(name2)){
				// 弹出Dialog 提示是否要进行删除
				zzxDialog.setTitle("是否提交");
				zzxDialog.setPositiveButton("确定", new OnClickListener() {
					public void onClick(View arg0) {
						// 实际开发这里会调接口 修改状态
						submit();
					}
				}).setNegativeButton("取消", new OnClickListener() {
					public void onClick(View arg0) {

					}
				}).show();
			}else{
				saomiao.close();
				useDialog.show();//弹出登录
				useDialog.setTitle("清分员登录");
			}
			break;

		case R.id.startsaomiao_qf:	// 开始扫描
			if(tflag){
				saomiao.start();
				tflag = false;
			}		
			break;
		case R.id.zzx_clear_qf:// 重新扫描
			boxlist.clear();
			if (bundle != null) {
				for (int i = 0; i < copylist.size(); i++) {
					boxlist.add(copylist.get(i));
				}
			}
			btn.setEnabled(false);
			btn.setBackgroundResource(R.drawable.gray_btn_bg);
			saomiao.open();
			saomiao.clear();
			list.clear();
			zhouzxAdapter.upListView(list);
			break;
		}
	}
	/**
	 * 提示是否提交
	 */
	public void sendSubmit(){
		// 弹出Dialog 提示是否要进行删除
		zzxDialog.setTitle("是否提交");
		zzxDialog.setPositiveButton("确定", new OnClickListener() {
			public void onClick(View arg0) {
				// 实际开发这里会调接口 修改状态
				submit();
			}
		}).setNegativeButton("取消", new OnClickListener() {
			public void onClick(View arg0) {

			}
		}).show();
	}
	
	/**
	 * 提交
	 */
	public void submit(){
		loginDiolag.show();
		loginDiolag.setMessage("提交中...");
		new Thread(new Runnable() {
			public void run() {
				try {
					String result = UpServer.setHuiKu(paigongdan, app.userZhanghao, qfId);;
					if("success".equals(result)){
						handler.sendEmptyMessage(3);
					}else{
						handler.sendEmptyMessage(2);
					}
				} catch (SocketException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(1);
				}catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(2);
				}
			}
		}).start();
	}
	
	/**
	 * 用户验证
	 */
	public void yanzhengUser(final String name,final String pwd){
		loginDiolag.show();
		loginDiolag.setMessage("正在验证用户...");
		new Thread(new Runnable() {	
			public void run() {
				try {
					user = UpServer.login(name, pwd);
					if(user!= null){
						handler.sendEmptyMessage(11);
					}else{
						handler.sendEmptyMessage(12);//查无此人信息
					}
				}catch (NullPointerException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(12);//查无此人信息
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(13);//登录异常
				}
			}
		}).start();
	}
	
	/**
	 * 重试
	 */
	public void reSubmit(){
		zzxDialog.show();
		zzxDialog.setGone();
		zzxDialog.setPositiveButton("重试", new OnClickListener() {
			public void onClick(View arg0) {
				
				submit();
			}
		}).setNegativeButton("取消", new OnClickListener() {
			public void onClick(View arg0) {

			}
		});
	}
	
	/**
	 * 用户登录失败重试
	 */
	public void OnLoginClick(){
		deleteDialog.show();
		deleteDialog.setTitle("登录异常");
		deleteDialog.setPositiveButton("重试", new OnClickListener() {
			public void onClick(View arg0) {
				yanzhengUser(userId, pwd);
			}
		});
		deleteDialog.setNegativeButton("取消", new OnClickListener() {		
			public void onClick(View arg0) {	
			}
		});
	}
	/**
	 * 扫描视图显示
	 */
	public void showView(){
		if(list.size()>0){
			zxlist_layout_view.setVisibility(View.VISIBLE);
			zxlist_layout.setVisibility(View.GONE);
		}else{
			zxlist_layout_view.setVisibility(View.GONE);
			zxlist_layout.setVisibility(View.VISIBLE);
		}
		zzxgridView.setAdapter(zhouzxAdapter);
		zhouzxAdapter.upListView(list);//刷新视图
		if(copylist.size()==list.size()){
			btn.setEnabled(true);
			btn.setBackgroundResource(R.drawable.buttom_selector_bg);
		}else{
			btn.setEnabled(false);
			btn.setBackgroundResource(R.drawable.gray_btn_bg);
		}
	}
	
	/**
	 * 登录后用户判断
	 */
	public void checkLogin(){
		if("".equals(qf_name1.getText().toString()) || qf_name1.getText().toString()==null){
			if(user.getUserId().equals(Constant.QfRoleId)){//清分员登录
				qfId = userId+"_";
				qf_name1.setText(user.getName());
				leftImage.setBackgroundResource(R.drawable.sccuss);
				if(flag){
					fristUserId = userId;//保存第一个人登录的账号	
					flag = false;
				}
				useDialog.show();
				useDialog.setTitle("清分员二登录");
			}else{
				useDialog.show();
				useDialog.setTitle("请用清分员登录");
			}			
		}else{
			if (user.getUserId().equals(Constant.QfRoleId)) {
				qfId = qfId + userId;
				qf_name2.setText(user.getName());
				rightImage.setBackgroundResource(R.drawable.sccuss);
				sendSubmit();
			} else {
				useDialog.show();
				useDialog.setTitle("清分员二登录");
			}
		}
	}
}
